/***** Setting *****/
var uploadBase = ''; // 图片和附件服务器地址和端口，如http://www.ueapp.net，本机留空
var jsHostBase = '';

var tmpImgUrl         = jsHostBase + 'images/admincp/ico-news.jpg';
var uploadUrl         = uploadBase + 'index.php?app=system&ctl=uploader&act=add&ajax=1';
var delImgUrl         = uploadBase + 'index.php?app=system&ctl=uploader&act=del&ajax=1';
var setAlbumCoverUrl  = uploadBase + 'index.php?app=system&ctl=uploader&act=setAlbumCover&ajax=1';
var getAlbumImgsUrl   = uploadBase + 'index.php?app=system&ctl=uploader&act=getAlbumByRid&ajax=1';
var imgListUrl        = uploadBase + 'index.php?app=system&ctl=uploader&act=list&ajax=1';
var loginUrl          = 'index.php?app=user&ctl=account&act=login&id='+encodeURIComponent(document.location.href);
/***** End Setting *****/


// 包含js
document.write('<script type="text/javascript" src="'+jsHostBase+'js/ajaxf.js"></script>');
document.write('<script type="text/javascript" src="'+jsHostBase+'js/editor/xheditor-zh-cn.min.js"></script>');
// 样式
document.write('<link id="uploader-style" type="text/css" rel="stylesheet" href="'+jsHostBase+'js/uploader/uploader.css" />');

var pageUrl = document.location.href;
var ctx = pageUrl.substr(0, pageUrl.lastIndexOf("/") + 1);

var mouseX = 0;
var mouseY = 0;
$(document).mousemove(function (e) {
    if (e.pageX || e.pageY) {
        mouseX = e.pageX;
        mouseY = e.pageY;
    } else if (e.clientX || e.clientY) {
        mouseX = e.clientX;
        mouseY = e.clientY;
    }
});

function ajaxStatusStart() {
    $('#ajax-loading').remove();
    $('body').append('<div id="ajax-loading"></div>');
    $('#ajax-loading').css('left', (mouseX - 50) + 'px');
    $('#ajax-loading').css('top', (mouseY - 64) + 'px');
}

function ajaxStatusStop() {
    $('#ajax-loading').remove();
}



// 如果没有登录则跳转到登录页面
function isBCVisiable() {
    if (typeof u == 'undefined') {
        alert('错误：需要在' + pageUrl + '的</title>后加入用户中心验证代码\n<script type="text/javascript" src="/Home/GetCurrentMember?isjs=1"></script>');
        return;
    }
    
    if (!u.user || !u.pass) {
        window.location = loginUrl;
    }
}


// 如果是用户中心则需要验证权限
if (ctx.substr(ctx.length - 15, 14) == 'BusinessCenter') {
    isBCVisiable();
}


$(document).ready(function () {
    $.ajaxf.init(jsHostBase+'js/AJAX.swf?' + Math.random());

    $(".note, .msg-list tr").hover(
		function () { $(this).addClass("note-hover"); },
		function () { $(this).removeClass("note-hover"); }
	);

    if (typeof u == 'undefined' || typeof u.user == 'undefined' || typeof u.pass == 'undefined') {
        return;
    }

});

function getServiceUrl(cls, method) {
    return KernelServicesBase + cls + '.svc/' + method
}

/**
* 获取请求GET变量
*/
function getQueryParam(item) {
    var svalue = location.search.match(new RegExp('[\?\&]' + item + '=([^\&]*)(\&?)', 'i'));
    return svalue ? decodeURIComponent(svalue[1]) : '';
}

var editorTools = 'Pastetext,|,Blocktag,Fontface,FontSize,Bold,Italic,Underline,Strikethrough,FontColor,BackColor,Removeformat,|,Align,List,Outdent,Indent,|,Link,Unlink,Img,Flash,Media,Emot,Table,|,Source,Fullscreen,About';

/**
* 重置编辑器的高度
*/
function editorHigher(px) {
    var xheHeight = $('.xheIframeArea').height() + px;
    if (xheHeight > 1200 || xheHeight < 100) return false;
    $('.xheIframeArea').css('height', xheHeight + 'px')
    $('.xheLayout').css('height', 'auto');
}

/**
 *
 */
function json2Reqstr(json) {
	var elements = new Array();
	if(typeof json == 'object') {
		for(var name in json) {
			json[name] = typeof json[name] == 'undefined' ? '' : json[name];
			elements.push(encodeURIComponent(name.toString()) + "=" + encodeURIComponent(json[name].toString()));
		}
	}
	
	return elements.join('&');
}
/**
* json 转 string,提供ajax POST用
*/
function json2String(json) {
    var s = '';
    for (var k in json) {
        if (s.length > 0) {
            s += ',';
        }
        if (typeof json[k] == 'object') {
            if (k == 'user') {
                s += '"user": ["' + json[k][0] + '", "' + json[k][1] + '"]';
            } else {
                s += '"' + jsonsAddSlashes(k) + '": ' + json2String(json[k]);
            }
        } else {
            s += '"' + jsonsAddSlashes(k) + '": "' + jsonsAddSlashes(json[k]) + '"';
        }
    }

    return '{' + s + '}';
}

function jsonsAddSlashes(string) {
    if (typeof string == 'undefined') {
        return '';
    }

    string = string.replace(/\\/g, '\\\\');  // \
    string = string.replace(/"/g, '\\\"');   // "
    string = string.replace(/\//g, '\\\/');  // /
    //string = string.replace(/\b/g, '\\b');   // \b
    //string = string.replace(/\f/g, '\\f');   // \f
    string = string.replace(/\n/g, '\\n');   // \n
    string = string.replace(/\r/g, '\\r');   // \r
    string = string.replace(/\t/g, '\\t');   // \t
    // \uXXXX

    return string;
}


/**
 * 使层可拖动
 * 
 * @param string o 可拖动层的id
 * @param string moveTag 光标显示为可移动的元素， 可用id，类，标签，如#xx、.xx或xx 
 */
function dragable(o, moveTag) {
    if (typeof o == "string") o = document.getElementById(o);

    if (typeof moveTag == "string") {
        moveTag = document.getElementById(moveTag);
        o.onmouseover = function (a) {
            moveTag.style.cursor = 'move';
        }

        o.onmouseout = function (a) {
            moveTag.style.cursor = 'normal';
        }
    }

    o.orig_x = parseInt(o.style.left) - document.body.scrollLeft;
    o.orig_y = parseInt(o.style.top) - document.body.scrollTop;
    o.orig_index = o.style.zIndex;    
    
    moveTag.onmousedown = function (a) {
        this.style.zIndex = 10000;
        var d = document;
        if (!a) a = window.event;
        var x = a.clientX + d.body.scrollLeft - o.offsetLeft;
        var y = a.clientY + d.body.scrollTop - o.offsetTop;

        d.ondragstart = "return false;"
        d.onselectstart = "return false;"
        d.onselect = "document.selection.empty();"

        if (o.setCapture) {
            o.setCapture();
        } else if (window.captureEvents) {
            window.captureEvents(Event.MOUSEMOVE | Event.MOUSEUP);
        }

        d.onmousemove = function (a) {
            if (!a) a = window.event;
            $('#' + o.id).css('left', a.clientX + document.body.scrollLeft - x + 'px');
            $('#' + o.id).css('top', a.clientY + document.body.scrollTop - y + 'px');

            o.orig_x = parseInt(o.style.left) - document.body.scrollLeft;
            o.orig_y = parseInt(o.style.top) - document.body.scrollTop;
        }

        d.onmouseup = function () {
            if (o.releaseCapture) {
                o.releaseCapture();
            } else if (window.captureEvents) {
                window.captureEvents(Event.MOUSEMOVE | Event.MOUSEUP);
            }

            d.onmousemove = null;
            d.onmouseup = null;
            d.ondragstart = null;
            d.onselectstart = null;
            d.onselect = null;
            o.style.cursor = "normal";
            o.style.zIndex = o.orig_index;
        }
    }

    var orig_scroll = window.onscroll ? window.onscroll : function () { };

    window.onscroll = function () {
        orig_scroll();
        o.style.left = o.orig_x + document.body.scrollLeft;
        o.style.top = o.orig_y + document.body.scrollTop;
    }
}

/**
* 在页面中创建弹出div窗口
* 窗口样式在global样式中
*
* @param width 窗口宽 （默认560）
* @param height 窗口高 （默认410）
*/
function creatPopBox(title, width, height, content, dragTag) {
    title = title || '';
    height = height || 410;
    width = width || 560;
    content = content || '<div class="floor-loading"></div>';

    var popBoxPos = PopBoxPos(width, height);
    $('#pop-box').css('left', popBoxPos.left + 'px');
    $('#pop-box').css('top', popBoxPos.top + 'px');

    $('#pop-box, #pop-box-out').remove();

    var style = ' left:' + popBoxPos.left + 'px;'
	          + ' top:' + popBoxPos.top + 'px;'
			  + ' height:' + ((parseInt(height) == 0) ? 'auto;' : height + 'px;')
			  + ' width:' + width + 'px;';

    var html = '<div id="pop-box-out"></div>'
			 + '<div id="pop-box" style="' + style + '">'
			 + '  <a class="close"></a>'
			 + '  <div class="pop-box-in">'
			 + '    <div class="in-wrap">'
			 + (title == '' ? '' : '<h1 id="pop-title" class="pop-title">' + title + '</h1>')
			 + '      <div id="pop-main">' + content + '</div>'
			 + '    </div>'
			 + '  </div>'
			 + '</div>'
    $('body').append(html);

    //dragable('pop-box', '.pop-title');

    $('#pop-box .close').click(function () { $('#pop-box, #pop-box-out').remove(); });

    $(window).resize(function () {
        if ($('#pop-box').height() == null) return;
        var popBoxPos = PopBoxPos(width, height);
        $('#pop-box').css('left', popBoxPos.left + 'px');
        $('#pop-box').css('top', popBoxPos.top + 'px');
    });
	
    if (typeof dragTag != 'undefined' && dragTag) {
        dragable(document.getElementById('pop-box'), dragTag);
    }
}

/**
* 隐藏弹出窗口
*
* @param int time 逐渐隐藏时间 单位为毫秒
*/
var hidePopBoxTO;
function hidePopBox(time) {
    if (typeof time == 'undefined') time = 1000;
    clearTimeout(hidePopBoxTO);
    hidePopBoxTO = setTimeout('removePopBox(' + time + ')', time);

    $('#pop-box-out').fadeOut(time);
    $('#pop-box').fadeOut(time);
}
/**
* 关掉浮动窗口
*/
function removePopBox() {
    $('#pop-box').remove();
    $('#pop-box-out').remove();
}
/**
* 获取浮动窗口层的位置
*/
function PopBoxPos(width, height) {
    var pageWidth = window.innerWidth;
    var pageHeight = window.innerHeight;
    if (typeof pageWidth != "number") {
        if (document.compatMode == "CSS1Compat") {
            pageWidth = document.documentElement.clientWidth;
            pageHeight = document.documentElement.clientHeight;
        } else {
            pageWidth = document.body.clientWidth;
            pageHeight = document.body.clientHeight;
        }
    }

    var top = ((pageHeight - height) / 3) + $(window).scrollTop();
    var left = (pageWidth - width) / 2 + $(window).scrollLeft();

    return { 'left': left, 'top': top };
}

function divLoadPage(div, url, json) {
    $.ajaxf.ready(function () {
        $(div).html('<div class="floor-loading"></div>');

        $.ajaxf.postText(url, json, function (r) {
            $(div).html(r);
        });

    });
}

function hidePageLoading(id) {
    $('.w').show();

    if (typeof id == 'undefined') {
        id = 'page-loading-div';
    }
    //alert(id);
    $('#' + id).remove();
}

function showPageLoading(id) {
    //$('.w').hide();
    if (typeof id == 'undefined') {
        id = 'page-loading-div';
    }

    $('body').append('<div id="' + id + '" class="page-loading floor-loading"></div>');
    var code = "hidePageLoading('" + id + "')";
    //alert(code);
    setTimeout(code, 8000);
}


/**
* 设置cookie
* 
* @param string name
* @param string value
* @param Day expireDays 多少天后过期
*/
function setCookie(name, value, expireDays) {
    var exp = '';

    if (expireDays != null) {
        var exDate = new Date();
        exDate.setDate(exDate.getDate() + expireDays);
        exp = ";expires=" + exDate.toGMTString();
    }

    document.cookie = name + "=" + escape(value) + exp + "; path=/";
}

/**
* 读取cookie
*
* @param string name
*/
function getCookie(name) {
    if (document.cookie.length > 0) {
        start = document.cookie.indexOf(name + "=");
        if (start != -1) {
            start = start + name.length + 1;
            end = document.cookie.indexOf(";", start);
            if (end == -1) end = document.cookie.length;

            return unescape(document.cookie.substring(start, end));
        }
    }

    return "";
}

/**
* 删除cookie
*
* @param string name
*/
function delCookie(name) {
    setCookie(name, "", -1);
}

/**
* 显示提示信息，过hideTime秒钟后消失
* 
* @param string content 内容
* @param string title 标题
* @param int width 提示框宽（可选）
* @param int height 提示框高（可选）
* @param int hideTime 提示框过多少秒后隐藏（可选）
*/
var showMsgTO;
function showMsg(content, title, width, height, hideTime) {
    title = title || '提示信息';
    width = width || 210;
    height = height || 100;
    hideTime = hideTime || 5000;

    clearTimeout(showMsgTO);
    showMsgTO = setTimeout('hidePopBox()', hideTime);

    content = '<div class="show-message">' + content + '</div>';
    creatPopBox(title, width, height, content, false);
}

function showMessage(content, title, width, height, hideTime) {
    showMsg(content, title, width, height, hideTime);
}

// 生成 UUID
function makeGuid() {
    var S4 = function () {
        return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
    };
	
    return S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + Math.random().toString(16).substr(2, 12);
}

function getDateTime() {
    var date = new Date();
    return date.getFullYear() + '-' + date.getMonth() + '-' + date.getDay() + ' ' + date.getHours() + ':' + date.getSeconds() + ':' + date.getMinutes();
}

/**
 * 检查ajax返回结果
 * @param jaon r
 * @return bool 正确则返回true，错误则处理并返回false
 */
function checkAjaxReturn(r) {
	if(r.err) {
		r.err.code = r.err.code || 0;
		// 没有登录
		if(r.err.code == 401) {
			r.err.text = r.err.text || '你没有权限访问该页面，即将跳转到登录页面！';
			showMessage(r.err.text);
			setTimeout('window.location.href=loginUrl', 3000);			
		}
		
		// 没有权限
		else if(r.err.code == 403) {
			r.err.text = r.err.text || '你没有权限访问该页面';
			showMessage(r.err.text);
		}
		
		// 页面不存在
		else if(r.err.code == 404) {
			r.err.text = r.err.text || '该页面不存在';
			showMessage(r.err.text);
			
		}
		
		else {
			r.err.text = r.err.text || 'AJAX请求错误！';
			showMessage(r.err.text);
		}
		
		return false;
	}
	return true;
}